package industry_2024.industry_09.extract

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.lit

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}

object extract_count {
  def main(args: Array[String]): Unit = {
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("数据抽取")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
//      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
//      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()


    spark.sql("use ods09")

    val connect=new Properties()
    connect.setProperty("user","root")
    connect.setProperty("password","123456")
    connect.setProperty("driver","com.mysql.jdbc.Driver")

    val day:Calendar=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)

    //  创建写入hive的方法
    def to_hive(mysql_name:String,hive_name:String):Unit={
      spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false",mysql_name,connect)
        .withColumn("etldate",lit(yesterday))
        .write.mode("append")
        .format("hive")
        .partitionBy("etldate")
        .saveAsTable(s"ods09.${hive_name}")
    }

    //  需要剔除字段的方法
    def to_hive02(mysql_name: String, hive_name: String): Unit = {
      spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false", mysql_name, connect)
        .drop("ProducePrgCode")
        .withColumn("etldate", lit(yesterday))
        .write.mode("append")
        .format("hive")
        .partitionBy("etldate")
        .saveAsTable(s"ods09.${hive_name}")
    }

    to_hive("EnvironmentData", "environmentdata")
    to_hive("ChangeRecord", "changerecord")
    to_hive("BaseMachine", "basemachine")
    to_hive02("ProduceRecord", "producerecord")
    to_hive("MachineData", "machinedata")

    spark.sql("select * from ods09.machinedata limit 5").show


    spark.close()
  }

}
